export const MessageFactory = {
  createTextMessage: function (conversationId, sender, receiver, content) {
    return {
      conversationId: conversationId,
      type: 'text',
      sender: sender,
      receiver: receiver,
      content: content,
      timestamp: Date.now()
    }
  },
  createFileMessage: function (conversationId, sender, receiver, url, name, size, format) {
    return {
      conversationId: conversationId,
      type: 'file',
      sender: sender,
      receiver: receiver,
      content: JSON.stringify({
        url: url,
        name: name,
        size: size,
        format: format
      }),
      timestamp: Date.now()
    }
  },
  parseMessage: function (message) {
    message = JSON.parse(message);
    console.log('message: ', message);

    switch (message.type) {
      case 'text':
        return this.parseTextMessage(message);
      case 'file':
        return this.parseFileMessage(message);
      default:
        throw new Error('Invalid message type');
    }
  },
  parseTextMessage: function (message) {

    if (message.type !== 'text')
      throw new Error('Invalid message type');

    return {
      conversationId: message.conversationId,
      type: 'text',
      sender: message.sender,
      receiver: message.receiver,
      content: message.content,
      timestamp: message.timestamp
    }
  },
  parseFileMessage: function (message) {

    if (message.type !== 'file')
      throw new Error('Invalid message type');

    const fileInfo = JSON.parse(message.content);

    return {
      conversationId: message.conversationId,
      type: 'file',
      sender: message.sender,
      receiver: message.receiver,
      content: message.content,
      url: fileInfo.url,
      name: fileInfo.name,
      size: fileInfo.size,
      timestamp: message.timestamp
    }
  }
}